package com.echovin.esb.gateway.filter;

import com.echovin.esb.gateway.constants.ErrorCode;
import com.echovin.esb.gateway.constants.OrderConstants;
import com.echovin.esb.gateway.exception.OpenException;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class WrapperResponseBodyGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        return chain.filter(exchange).then(Mono.fromRunnable(()->{
//            ServerHttpResponse originalResponse = exchange.getResponse();
//            HttpStatus status = originalResponse.getStatusCode();
//            if (status != HttpStatus.OK) {
//                throw new OpenException(ErrorCode.THIRD_SERVICE_ERROR.getCode());
//            }
//        }));
        //获取response的 返回数据
        ServerHttpResponse originalResponse = exchange.getResponse();
        DataBufferFactory bufferFactory = originalResponse.bufferFactory();
        HttpStatus statusCode = originalResponse.getStatusCode();
        if (statusCode == HttpStatus.OK) {
            ServerHttpResponseDecorator decorate = new ServerHttpResponseDecorator(originalResponse) {
                @Override
                public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                    Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                    return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
                        DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                        DataBuffer join = dataBufferFactory.join(dataBuffers);
                        byte[] content = new byte[join.readableByteCount()];
                        join.read(content);
                        DataBufferUtils.release(join);
                        String responseData = new String(content, StandardCharsets.UTF_8);
                        HttpStatus status = originalResponse.getStatusCode();
                        if (status != HttpStatus.OK) {
                            throw new OpenException(ErrorCode.THIRD_SERVICE_ERROR.getCode());
                        }
                        //responseData就是下游系统返回的内容,可以查看修改
                        log.info("响应内容:{}", responseData);
                        byte[] uppedContent = new String(responseData.getBytes(), Charset.forName("UTF-8")).getBytes();
                        return bufferFactory.wrap(uppedContent);
                    }));
                }
            };
            return chain.filter(exchange.mutate().response(decorate).build());
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        //-1 is response write filter, must be called before that
        return OrderConstants.WRAPPER_RESPONSE;
    }
}
